<?php
/**
 * Created by PhpStorm.
 * User: 刘海平（785313152）
 * Date: 2019/4/1
 * Time: 11:20
 * Message: 对未来没概念，也不想有概念，脑子里只关心汤面会不会太咸！
 */

namespace app\index\controller;



use think\Controller;
use think\Session;

class Login extends Controller
{

    public function index(){
        $code = input('code');
        $state = input('state');
        if($code&&($state=='jdz')){
            $access_token = get_access_token();
            $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$access_token.'&code='.$code;
            $res = httpGet($url);
            $res = json_decode($res,true);
            if($res['errcode']==0) {
                $get_userid_url = 'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token='
                    . $access_token . '&userid=' . $res['UserId'];
                $user_info = json_decode(httpGet($get_userid_url), true);
                if ($user_info['errcode']==0){
                    //查找数据库中是否已保存该成员
                    if(!model('User')->find($user_info['userid'])){
                        $data['user_id'] = $user_info['userid'];
                        $data['user_name'] = $user_info['name'];
                        $data['add_time'] = date('Y-m-d H:i:s');
                        $data['user_head'] = $user_info['avatar'];
                        $data['avatar'] = $user_info['avatar'];
                        $data['name']=$user_info['name'];
                        model('User')->save($data);
                    }
                    Session::set('user_info',$user_info);
                    if(Session::get('location_url')){
                        $this->redirect(Session::get('location_url'));
                    }
                    $this->redirect('index/index');
                }
            }
        }else{
            $uri = urlencode(site_url. '/index/login/index'); //授权成功返回地址
            //下面$url请求授权登录地址,设置的是手动授权
            $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='
                .get_appId().'&redirect_uri='
                .$uri.'&response_type=code&scope=snsapi_base&state=jdz#wechat_redirect';
            header('Location:' . $url);exit;
        }
    }


}